import requests
from PIL import Image
import os
import matplotlib.pyplot as plt


def spilt(imgFile, H=4, V=1):
    imgFileNameList = []
    ImgObj = Image.open(imgFile)
    imgFileName = os.path.split(imgFile)[1]
    imgFileName = imgFileName[:imgFileName.rindex('.')]
    for i in imgFileName:
        imgFileNameList.append(i+".jpg")
    crtW, crtH = ImgObj.size
    hStep = crtW // H
    vStep = crtH // V
    for i in range(V):
        for j in range(H):
            OutFileNameTemp = imgFileNameList[j][:imgFileNameList[j].rindex('.')]
            OutFileName = os.path.join("code",OutFileNameTemp,imgFileNameList[j])
            if not os.path.isdir(os.path.join("code",OutFileNameTemp)):
                os.mkdir(os.path.join("code",OutFileNameTemp))
            OutNewFileName = OutFileName
            if os.path.isfile(OutFileName):
                OutNewFileName = OutFileName[:OutFileName.rindex('.')] + \
                              '_cp' \
                              + OutFileName[OutFileName.rindex('.'):]
            box = (j * hStep, i * vStep, (j + 1) * hStep, (i + 1) * vStep)
            cropped = ImgObj.crop(box)
            cropped.save(OutNewFileName)

def Get_vcode():
    result = requests.get("http://jwgl.hist.edu.cn/jwweb/sys/ValidateCode.aspx")
    # 下载验证码
    if not os.path.isdir("code"):
        os.mkdir("code")
        if not os.path.isdir("code/all"):
            os.mkdir("code/all")
    with open('code/all/vcode.jpg', 'wb') as f:
        f.write(result.content)
    f.close()

def Show():
    # 显示验证码
    # img = Image.open('code/all/vcode.jpg')
    # img.show()
    # code = input("请输入验证码:")
    # img.close()
    # return code

    img = Image.open('code/all/vcode.jpg')
    plt.figure("dog")
    plt.imshow(img)
    plt.show()
    plt.close()
    code = input("请输入验证码:")
    
    return code


def rename(oldfile, newFile):
    newFileTemp = newFile
    if os.path.isfile(newFile):
       newFileTemp = newFile[:newFile.rindex('.')] + \
                             '_cp'\
                             + newFile[newFile.rindex('.'):]
    os.rename(oldfile, newFileTemp)

if __name__ == '__main__':
    for i in range(1):
        Get_vcode()
        code = Show()
        NewCodeFile = os.path.join("code\\all",code+".jpg")
        rename("code/all/vcode.jpg", NewCodeFile)
        spilt(NewCodeFile)
        print("第{}张ok!".format(i+1))